var express = require('express');
var fs = require('fs');
var path = require('path');
var app = express();
app.use(express.static('static'));
//post请求的中间件
app.use(express.json());
app.use(express.urlencoded({extended: false}));

//注册
app.post('/register',(req,res)=>{
    var {phone} = req.body;
    //读取users.json文件中的数据
    var filepath = path.join(__dirname,'./json/users.json');
    var arr = fs.readFileSync(filepath);
    arr = arr.toString()?JSON.parse(arr):[];

    var i =arr.findIndex((item)=>{
        return item.phone == phone;
    })
    if(i != -1){
        res.send({code:400,msg:'用户已存在，注册失败！！'})
    }else{
        arr.push( {...req.body,ingroup:'保全组',isadmin:true,status:true} )
        fs.writeFileSync(filepath, JSON.stringify( arr ), 'utf8' );
        res.send({code:200,msg:'注册成功!'})
    }
})

//分页请求
app.get('/user/list', (req, res) => {
    var {page, count} = req.query;

    //读取users.json文件中的数据
    var filepath = path.join(__dirname,'./json/users.json');
    var arr = fs.readFileSync(filepath);
    arr = arr.toString()?JSON.parse(arr):[];

    var newarr = arr.slice((page - 1) * count, page * count);
    res.send({code: 200, msg: '请求成功!', list: newarr});
})

//搜索
app.get('/user/search', (req, res) => {
    var {searchkey} = req.query;

    //读取users.json文件中的数据
    var filepath = path.join(__dirname,'./json/users.json');
    var arr = fs.readFileSync(filepath);
    arr = arr.toString()?JSON.parse(arr):[];

    var newarr = arr.filter((item) => {
        return new RegExp(searchkey).test(item.name);
    })
    res.send({code: 200, msg: '查询成功!', list: newarr});
})

//登录
app.post('/user/login', (req, res) => {
    var {phone, pass} = req.body;

    //读取users.json文件中的数据
    var filepath = path.join(__dirname,'./json/users.json');
    var arr = fs.readFileSync(filepath);
    arr = arr.toString()?JSON.parse(arr):[];

    var i = arr.findIndex((item, index) => {
        return item.phone == phone && item.pass == pass;
    })
    if (i != -1) {
        res.send({code: 200, msg: '登陆成功!',userinfo: arr[i]});
    } else {
        res.send({code: 400, msg: '登陆失败!'});
    }
})

//设置监听
app.listen(2022, () => {
    console.log('服务端运行在: http://localhost:2022');
})
